<?php

Class DepositSubmission extends DataObject implements PermissionProvider {
    private static $singular_name = "Deposit Submission";
    private static $plural_name = "Deposit Submissions";
   
	private static $payment_methods = array('BankPayment' => true);
    private static $template = 'DepositStatementTemplate';
    
    private static $db = array(
        'Amount' => 'Currency',
        'Status' => "Enum(array('Pending', 'Process', 'Partially Paid', 'Fully Paid', 'Approved', 'Voided', 'Canceled'), 'Pending')",
        'PaidDate' => 'Datetime',
        'VoidedDate' => 'Datetime',
        'Remark' => 'Varchar(255)'
    );
    
    private static $has_one = array(
        'PaymentReceipt' => 'Receipt',
        'Member' => 'Member',
        'Admin' => 'Member'
    );
    
    private static $many_many = array(
        'PurchaseAccounts' => 'PurchaseAccount'
    );
    
    private static $default_sort = "Created DESC";

    private static $searchable_fields = array(
        'Created',
        'PaymentReceipt.Reference',
        'Member.Username',
        'Member.FirstName',
        'Member.Surname',
        'Status'
    );

    private static $summary_fields = array(
        'Created.Nice',
        'PaymentReceipt.Reference',
        'Member.Username',
        'Member.Name',
        'Amount',
        'Status',
        'Admin.Username'
    );
    
    static function create_deposit_submission($data, $memberid){
        $id = DepositSubmission::create()->update($data)->setField('MemberID', $memberid)->write();
        return DepositSubmission::get()->byID($id);
    }
    
    static function update_status($id, $status, $remark = false) {
        $deposit_submission = DepositSubmission::get()->byID($id);
        if(!$deposit_submission){
            return false;
        }

        if($status == 'Fully Paid') {
            $deposit_submission->PaidDate = SS_Datetime::now()->getValue();
        }

        if($status == 'Voided') {
            $deposit_submission->VoidedDate = SS_Datetime::now()->getValue();
            $depositPurchaseStatements = $deposit_submission->PurchaseAccounts()->filter('Type', 'Deposit')->filter('Description', "Refund - " . $deposit_submission->PaymentReceipt()->TransactionType()->Description)->filter('Reference', $deposit_submission->PaymentReceipt()->Reference)->filter('Debit:GreaterThan', 0);
            if($depositPurchaseStatements->count()) {
                if(!$deposit_submission->PurchaseAccounts()->filter('Type', 'Deposit')->filter('Description', $deposit_submission->PaymentReceipt()->TransactionType()->Description)->filter('Reference', $deposit_submission->PaymentReceipt()->Reference)->filter('Credit:GreaterThan', 0)->count()) {
                    foreach($depositPurchaseStatements as $depositPurchaseStatement) {
                        $data = array(
                            'Type' => $depositPurchaseStatement->Type,
                            'Debit' => $depositPurchaseStatement->Credit,
                            'Reference' => $depositPurchaseStatement->Reference,
                            'Description' => 'Refund - '.$deposit_submission->PaymentReceipt()->TransactionType()->Description
                        );
                        $deposit_submission->PurchaseAccounts()->add(PurchaseAccount::create_statement($data, $depositPurchaseStatement->MemberID));
                    }
                }
            }
        }
        
        if($status == 'Approved') {
            if(!$count = $deposit_submission->PurchaseAccounts()->filter('Type', 'Deposit')->filter('Description', $deposit_submission->PaymentReceipt()->TransactionType()->Description)->filter('Reference', $deposit_submission->PaymentReceipt()->Reference)->filter('Credit:GreaterThan', 0)->count()) {
                $data = array(
                    'Type' => 'Deposit',
                    'Credit' => $deposit_submission->Amount,
                    'Reference' => $deposit_submission->PaymentReceipt()->Reference,
                    'Description' => 'Load Deposit'
                );
                $deposit_submission->PurchaseAccounts()->add(PurchaseAccount::create_statement($data, $deposit_submission->MemberID));
            }
        }

        if($remark !== false) {
            $deposit_submission->Remark = $remark;
        }
        $deposit_submission->Status = $status;
        $deposit_submission->write();
        return $deposit_submission->ID;
    }
    
    /**
     * Set deposit statement template
     * 
     * @param $set_template string
     */
    static function set_template($set_template) {
    	Config::inst()->update('DepositSubmission', 'template', $set_template);
    }
    
    /**
     * Get deposit statement template
     * 
     * @param string
     */
    static function get_template() {
        return Config::inst()->get('DepositSubmission', 'template');
    }
	
	function requireDefaultRecords() {
        if(!$type = TransactionType::get()->find('Code', 'DEPOSIT')) {
            TransactionType::create()
            ->setField('Code', 'DEPOSIT')
            ->setField('Title', 'Load Deposit')
			->setField('Description', 'Load deposit')
            ->setField('Object', 'DepositSubmission')
            ->setField('Page', 'DepositStatementPage')
            ->write();
            DB::alteration_message('Deposit transaction type created', 'created');
        }
    }
	
	public function fieldLabels($includerelations = true) {
		$labels = parent::fieldLabels($includerelations);
		
		$labels['Created'] = _t('DepositSubmission.SUBMIT_ON', 'Submit On');
		$labels['Created.Nice'] = _t('DepositSubmission.SUBMIT_ON', 'Submit On');
		$labels['Amount'] = _t('DepositSubmission.AMOUNT', 'Amount');
		$labels['Status'] = _t('DepositSubmission.STATUS', 'Status');
		$labels['PaidDate'] = _t('DepositSubmission.PAID_DATE', 'Paid Date');
		$labels['VoidedDate'] = _t('DepositSubmission.VOIDED_DATE', 'Voided Date');
		$labels['Remark'] = _t('DepositSubmission.REMARK', 'Remark');
		$labels['PaymentReceipt.Title'] = _t('DepositSubmission.METHOD', 'Method');
		$labels['PaymentReceipt.Reference'] = _t('DepositSubmission.REFERENCE', 'Reference');
		$labels['Admin.Username'] = _t('DepositSubmission.UPDATED_BY', 'Updated By');
		$labels['Member.Username'] = _t('DepositSubmission.USERNAME', 'Username');
		$labels['Member.Name'] = _t('DepositSubmission.NAME', 'Name');
		$labels['Member.FirstName'] = _t('DepositSubmission.FIRSTNAME', 'First Name');
		$labels['Member.Surname'] = _t('DepositSubmission.SURNAME', 'Surname');
		
		return $labels;	
	}
	
	function validate() {
        $validationResult = parent::validate();
		if(!$this->ID && $this->Amount <= 0){
			$subvalid = new ValidationResult();
            $subvalid->error(_t('DepositSubmission.INVALID_DEPOSIT_AMOUNT', "Invalid deposit amount"), "INVALID_DEPOSIT");
            $validationResult->combineAnd($subvalid);
		}

        return $validationResult;
    }
    
    function getCMSFields() {
        $fields = parent::getCMSFields();
        if($this->exists()){
            $fields = FieldList::create(
                 LiteralField::create('Statement', $this->ViewHTML())
            );
        }
        
        return $fields;
    }
    
    function getDepositFormFields($memberid){
        $fields = FieldList::create(
        	HiddenField::create('MemberID', 'MemberID', $memberid),
            HiddenField::create('PurchaseAccountBalance', 'PurchaseAccountBalance', Account::get('PurchaseAccount', $memberid)->Balance),
            $balance_field = ReadonlyField::create('ShowPurchaseAccountBalance', _t('DepositSubmission.CURRENT_BALANCE', 'Current Balance'), Account::get('PurchaseAccount', $memberid)->obj('Balance')->Nice()),
            DepositAmountField::create('Amount', _t('DepositSubmission.AMOUNT', 'Amount'))
        );
        $balance_field->setIncludeHiddenField(true);
        $this->extend('updateDepositFormFields', $fields);
        
        return $fields;
    }

    function getFullDetailHTML() {
        $this->Format = 'HTML';
		$this->PaymentReceipt()->Format = 'HTML';
        $template = new SSViewer('DepositStatementDetail');
        $template->includeRequirements(false);
        return $this->renderWith($template);
    }
    
    function getAction(){
        $extra_action = '';
        foreach($this->PaymentReceipt()->Payments() as $payment) {
            if($action = $payment->getAction()) {
                $extra_action .= $action;
            }
        }
        $view_link = Controller::join_links(DepositStatementPage::get()->First()->Link('view_statement'), $this->ID);
        $action = sprintf('<div class="btn-group"><button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">%s <span class="caret"></span></button><ul class="dropdown-menu dropdown-menu-right"><li><a title="%s" data-title="%s" rel="popup tooltip" href="%s">%s</a></li>%s</ul></div>', _t('DepositSubmission.ACTION', 'Action'), _t('DepositSubmission.CLICK_DEPOSIT_DETAILS', 'Click here to view deposit details'), _t('DepositSubmission.DEPOSIT_DETAILS', 'Deposit Details'), $view_link, _t('DepositSubmission.BUTTONVIEW', 'View'), $extra_action);

        return $action;
    }
    
    function Items(){
        $item = array(
            'UnitAmount' => $this->Amount,
            'Quantity' => 1,
            'ProductTitle' => 'Load Deposit'
        );
        return ArrayData::create($item);
    }
    
    function ViewHTML(){
        $template_ss = self::get_template();
        $this->PrintTime = SS_Datetime::now()->Nice();
        $this->Format = 'HTML';
        $this->SiteConfig = SiteConfig::current_site_config();
		$this->PaymentReceipt()->Format = 'HTML';
        $template = new SSViewer($template_ss);
        $template->includeRequirements(false);
        return $this->renderWith($template);
    }
    
    function ViewPDF(){
    	if($this->config()->allowed_pdf && class_exists('SS_DOMPDF')){
	        $template_ss = self::get_template();
	        $this->PrintTime = SS_Datetime::now()->Nice();
	        $this->Format = 'PDF';
	        $this->SiteConfig = SiteConfig::current_site_config();
			$this->PaymentReceipt()->Format = 'PDF';
	        $template = new SSViewer($template_ss);
	        $template->includeRequirements(false);
			$pdf = new SS_DOMPDF();
			$pdf->setHTML($this->renderWith($template));
			$pdf->render();
			return $pdf->stream(sprintf('load_deposit_%s.pdf', $this->PaymentReceipt()->Reference));
		}
    }
    
    function ViewPrint(){
        $template_ss = self::get_template();
        $this->PrintTime = SS_Datetime::now()->Nice();
        $this->Format = 'PRINT';
        $this->SiteConfig = SiteConfig::current_site_config();
		$this->PaymentReceipt()->Format = 'PRINT';
        $template = new SSViewer($template_ss);
        $template->includeRequirements(false);
        return $this->renderWith($template);
    }

    function canView($member = false) {
        $extended = $this->extendedCan(__FUNCTION__, $member);
        if($extended !== null) {
            return $extended;
        }
        return Permission::check('VIEW_DepositSubmission');
    }

    function canEdit($member = false) {
        return false;
    }

    function canDelete($member = false) {
        return false;
    }

    function canCreate($member = false) {
        return false;
    }
	
	function canPrint($member = false) {
        $extended = $this->extendedCan(__FUNCTION__, $member);
        if($extended !== null) {
            return $extended;
        }
        return Permission::check('PRINT_DepositSubmission');
    }
	
	function canApprove($member = false) {
        $extended = $this->extendedCan(__FUNCTION__, $member);
        if($extended !== null) {
            return $extended;
        }
        return $this->Status == 'Fully Paid' && Permission::check('APPROVE_DepositSubmission');
    }

    public function providePermissions() {
        return array(
            'VIEW_DepositSubmission' => array(
                'name' => _t('DepositSubmission.PERMISSION_VIEW', 'Allow view access right'),
                'category' => _t('DepositSubmission.PERMISSIONS_CATEGORY', 'Deposit Submission')
            ),
            'PRINT_DepositSubmission' => array(
                'name' => _t('DepositSubmission.PERMISSION_PRINT', 'Allow print access right'),
                'category' => _t('DepositSubmission.PERMISSIONS_CATEGORY', 'Deposit Submission')
            ),
            'APPROVE_DepositSubmission' => array(
                'name' => _t('DepositSubmission.PERMISSION_APPROVE', 'Allow approve access right'),
                'category' => _t('DepositSubmission.PERMISSIONS_CATEGORY', 'Deposit Submission')
            )
        );
    }

}
?>